package data

import (
	"context"
	"digitalhuman/internal/conf"
	"digitalhuman/models"
	"errors"
	"os"
	"sync"
)

type AssetData struct {
	Data         *Data
	BucketClient *OssAli
	AssetMap     map[int]*models.Asset // 本地缓存 asset
	lock         sync.Mutex
}

func (u *AssetData) FindByID(ctx context.Context, i int) (*models.Asset, error) {
	var asset *models.Asset
	u.Data.Db.Where("id = ?", i).First(&asset)
	if asset == nil {
		return nil, errors.New("asset not exist")
	}
	return asset, nil
}

func (u *AssetData) FindListByType(ctx context.Context, typeId int) ([]*models.Asset, error) {
	var assets []*models.Asset
	u.Data.Db.Where("type = ?", typeId).Find(&assets)
	if assets == nil {
		return nil, errors.New("assets not exist")
	}
	return assets, nil
}

func (u *AssetData) FindAll(ctx context.Context) ([]*models.Asset, error) {
	var assets []*models.Asset
	u.Data.Db.Find(&assets)
	if assets == nil {
		return nil, errors.New("assets not exist")
	}
	return assets, nil
}

func SyncDefaultAsset(oss *OssAli) error {
	// 读取/static目录下的文件
	dir, err := os.ReadDir("./static")
	if err != nil {
		return err
	}
	for _, d := range dir {
		err = oss.PutObjectFromLocalFile("./static/" + d.Name())
		if err != nil {
			panic(err)
		}
	}

	return nil
}

func (u *AssetData) FindAssetFromAssetMap(assetId int) *models.Asset {
	u.lock.Lock()
	defer u.lock.Unlock()

	return u.AssetMap[assetId]
}

func NewAssetData(data *Data, bc *OssAli, c *conf.Data) *AssetData {
	asset := &AssetData{
		Data:         data,
		BucketClient: bc,
	}
	asset.AssetMap = make(map[int]*models.Asset)
	allAssetData, err := asset.FindAll(context.Background())
	if err != nil {
		return nil
	}

	preUrl := "https://" + c.OssAli.Bucket + "." + c.OssAli.Endpoint
	if allAssetData != nil {
		for _, a := range allAssetData {
			a.Thumbnail = preUrl + a.Thumbnail
			asset.AssetMap[a.ID] = a
		}
	}

	return asset
}
